/**
 * 
 */
package iterator;

import index.IndexException;

import index.IndexScan;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import tests.GetStuff;

import diskmgr.rdfDB;

import btree.BTreeFile;
import btree.Interface3;
import btree.RdbIndexType;
import btree.StringKey;
import bufmgr.PageNotReadException;

import global.AttrOperator;
import global.AttrType;
import global.IndexType;
import global.PageId;
import global.RID;
import heap.BasicPattern;
import heap.FieldNumberOutOfBoundException;
import heap.HFBufMgrException;
import heap.HFDiskMgrException;
import heap.HFException;
import heap.InvalidTupleSizeException;
import heap.InvalidTypeException;
import heap.NodeID;
import heap.StringLabel;
import heap.Triple;
import heap.TripleHeapfile;
import heap.Tuple;
import btree.KeyCombine;
/**
 * @author smriti
 *
 */
public class BP_Triple_Join {

	/**
	 * @param amt_of_mem - available pages for the operation
	 * @param num_left_nodes - the number of node IDs in the left basic pattern stream
	 * @param left_itr - the left basic pattern stream
	 * @param BPJoinNodePosition - the position of the join node in the basic pattern
	 * @param JoinOnSubjectorObject - 0: join on subject; 1: join on object
	 * @param RightSubjectFilter - subject filter for the right source
	 * @param RightPredicateFilter - predicate filter for the right source
	 * @param RightObjectFilter - object filter for the right source
	 * @param RightConfidenceFilter - confidence filter for the right source
	 * @param LeftOutNodePositions - positions of the projected nodes from the left source.
	 * @param OutputRightSubject - 0/1 project subject node from the right source?
	 * @param OutputRightObject - 0/1 project object node from the right source?
	 */
	BP_Triple_Join( int amt_of_mem, int num_left_nodes, BPIterator left_itr,
			int BPJoinNodePosition, int JoinOnSubjectorObject, java.lang.String
			RightSubjectFilter, java.lang.String RightPredicateFilter, java.lang.String
			RightObjectFilter, double RightConfidenceFilter, int [] LeftOutNodePositions,
			int OutputRightSubject, int OutputRightObject){

	}

	public static Iterator getInitialBasicPattern() throws JoinsException, IndexException, InvalidTupleSizeException, InvalidTypeException, PageNotReadException, PredEvalException, SortException, LowMemException, UnknowAttrType, UnknownKeyTypeException, Exception{
		AttrType[] in = {new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrInteger),new AttrType(AttrType.attrInteger),
				new AttrType (AttrType.attrInteger),
				new AttrType (AttrType.attrInteger),
				new AttrType (AttrType.attrInteger), 
				new AttrType (AttrType.attrReal)};
		short [] Ssizes = null;
		FldSpec [] Rprojection = {new FldSpec(new RelSpec(RelSpec.outer), 1), 
				new FldSpec(new RelSpec(RelSpec.outer), 2),
				new FldSpec(new RelSpec(RelSpec.outer), 5),
				new FldSpec(new RelSpec(RelSpec.outer), 6),
				new FldSpec(new RelSpec(RelSpec.outer), 7)};
		Iterator tr = new FileScan("triples1", in, Ssizes, (short)7, 5, Rprojection, null);
		
		return tr;

	}


	private static  RID getBasicPatternID(BasicPattern BP) throws IndexException,
	UnknownKeyTypeException, IOException, InvalidTypeException,
	InvalidTupleSizeException, FieldNumberOutOfBoundException {

		KeyCombine combine = new KeyCombine();

		AttrType[] attrType = new AttrType[1];
		attrType[0] = new AttrType(AttrType.attrString);
		short[] attrSize = {50};

		CondExpr[] expr = new CondExpr[2];
		expr[0] = new CondExpr();
		expr[0].op = new AttrOperator(AttrOperator.aopEQ);
		expr[0].type1 = new AttrType(AttrType.attrSymbol);
		expr[0].type2 = new AttrType(AttrType.attrString);
		expr[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1);
		expr[0].operand2.string = combine.combineStrBP(BP);
		expr[0].next = null;
		expr[1] = null;

		FldSpec [] projlist = {new FldSpec(new RelSpec(RelSpec.outer), 1)};

		IndexScan iscan = null;
		try {
			iscan = new IndexScan(new IndexType(IndexType.B_Index), "BPHeap" ,
					"BTreeIndex_BP1", attrType, attrSize, 1, 1,
					projlist, expr, 1, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		RID _rid = new RID();
		iscan.get_next(_rid, true);
		System.out.println(_rid.pageNo+" , "+_rid.slotNo);
		iscan.close();
		return _rid;
	}

//	public static void insertBP(Interface3 i3) throws JoinsException, PageNotReadException, PredEvalException, SortException, LowMemException, UnknowAttrType, Exception{
//		System.out.println("*************Inserting into BP*************");
////		Interface3 i3 = new Interface3();
//		//	TripleHeapfile BPHeap = new TripleHeapfile("BPHeap");
//		
//		//	i3.createIndex(BPHeap, RdbIndexType.OC);
//		Iterator p = getInitialBasicPattern();
//		BasicPattern BP = null;
//		BTreeFile btf = new BTreeFile("BTreeIndex_BP1");
//		KeyCombine kc = new KeyCombine();
//		AttrType [] types = {new AttrType (AttrType.attrInteger),
//				new AttrType (AttrType.attrInteger),
//				new AttrType (AttrType.attrInteger),
//				new AttrType (AttrType.attrInteger),
//				new AttrType (AttrType.attrReal)};
//		
//		Tuple tupp = p.get_next();
//		while(tupp!=null)
//		{
//
//			//System.out.println(tupp.getIntFld(1) + "," + tupp.getIntFld(2)+ "," + tupp.getIntFld(3) + "," + tupp.getIntFld(4) + ","+ tupp.getFloFld(5));
////			System.out.println("Checking if a record with the same combination exists...");
//
////			NodeID id1 = new NodeID(new PageId(tupp.getIntFld(1)),tupp.getIntFld(2));
////			NodeID id2 = new NodeID(new PageId(tupp.getIntFld(3)),tupp.getIntFld(4));
////			float confidence = tupp.getFloFld(5);
////			BP = new BasicPattern(id1, id2, confidence);
//			BP = new BasicPattern(2, (short)5, types);
//			BP.tupleCopy(tupp);
//			RID	rid = getBasicPatternID(BP);
//
//
//			if (i3.isRIDModified(rid)) {
////				System.out.println("Oops! There is an entry with the same combination. Lets check if confidence has reduced");
//
//				Tuple tuple = i3.BPHeap.getRecord(rid);
//				BP.tupleCopy(tuple);
//
//				if (BP.getFloFld(5) > tupp.getFloFld(5) ) {
//					System.out.println("The confidence value is low. Need to be updated");
//					BP.setConfidence(tupp.getFloFld(5));
//
//					i3.BPHeap.updateRecord(rid, BP);
//					System.out.println("Updation complete");
//				} 
//			}else{
//				rid = i3.BPHeap.insertRecord(BP.getTupleByteArray());
//				//    i3.addIndex(RdbIndexType.SO, tupp, rid, "BTreeIndex_SO0");
////				System.out.println("Inserted into heap :"+rid.pageNo.pid +","+rid.slotNo);
//				String key = kc.combineStrBP(BP);
//				btf.insert(new StringKey(key), rid);
//				System.out.println("Added Key " + key + " to Index " + "BTreeIndex_BP1");
//			}
//			tupp = p.get_next();
//
//		}
//
//	}
	public static void main(String[] args) throws Exception {
		Interface3 i = new Interface3();
		i.superinit("/tmp/db", 1000, 1);
		i.init("test", 1000, 1);
		String[] dataval= null;
		String[] dataval2= null;
		try{
			String datafilename="//home//indrani//Downloads//minjava//DBI_phase2//src//tests//phase2_quarter.txt";
			FileReader f=new FileReader(datafilename);

			BufferedReader in = new BufferedReader(f);
			String str;
			while ((str = in.readLine()) != null) {
				try{
					dataval=str.split(":");	
					dataval2=dataval[3].split("\\s+");
					String confidence=dataval2[1];
					i.insertTriple(dataval[1].trim(),dataval[2].trim(),dataval2[0].trim(),Float.parseFloat(confidence),RdbIndexType.ALL);
				}
				catch(Exception e)
				{continue;}
			}
		} catch (IOException e) {
			throw new Exception("ERROR OPENING THE FILE:. Please verify the filename");
		}

		//		BP_Triple_Join.getInitialBasicPattern();
//		BP_Triple_Join.insertBP(i);
	}

}
